import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Button, Modal, message, Input, Spin, Typography, Tooltip } from 'antd';
import { useAnalysisStore } from '@/stores/analysisStore';
import CodeMirror, { ReactCodeMirrorRef } from '@uiw/react-codemirror';
import { html } from '@codemirror/lang-html';
import { vscodeDark } from '@uiw/codemirror-theme-vscode';
import { SendOutlined, ExpandOutlined, RobotOutlined, SyncOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { AIService } from './aiService';
import styles from './index.module.less';

const { TextArea } = Input;
const { Text } = Typography;

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: NodeJS.Timeout | null = null;
  return (...args: any[]) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
};

// 包装HTML，使链接不可点击但可以与其他元素交互
export const wrapHtmlWithNoClickStyle = (html: string) => {
  return `
    <html>
      <head>
        <style>
          * {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
          }
          body {
            padding: 16px;
            margin: 0;
            overflow-y: auto;
            height: 100%;
          }
          /* 禁用链接点击但保留原有样式 */
          a {
            pointer-events: none;
            color: #1677ff;
            text-decoration: underline;
            cursor: default;
          }
          pre {
            background-color: #f6f8fa;
            padding: 16px;
            border-radius: 6px;
            overflow-x: auto;
            white-space: pre-wrap;
            word-break: break-all;
          }
          code {
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
            background-color: rgba(175, 184, 193, 0.2);
            padding: 0.2em 0.4em;
            border-radius: 6px;
            font-size: 85%;
          }
          pre code {
            background-color: transparent;
            padding: 0;
          }
          table {
            border-collapse: collapse;
            width: 100%;
            margin: 16px 0;
          }
          th, td {
            border: 1px solid #d0d7de;
            padding: 8px;
            text-align: left;
          }
          th {
            background-color: #f6f8fa;
          }
          img {
            max-width: 100%;
            height: auto;
          }
          blockquote {
            padding: 0 1em;
            color: #57606a;
            border-left: 0.25em solid #d0d7de;
            margin: 1em 0;
          }
          hr {
            height: 0.25em;
            padding: 0;
            margin: 24px 0;
            background-color: #d0d7de;
            border: 0;
          }
        </style>
      </head>
      <body>${html}</body>
    </html>
  `;
};

// 简单的HTML语法高亮函数
const highlightHtml = (code: string): React.ReactNode => {
  if (!code) return null;
  
  // 替换HTML标签，使其高亮
  const highlightedCode = code
    // 处理开始标签和属性
    .replace(/(&lt;|<)(\/?)([\w\-]+)((?:\s+[\w\-:]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[\w\-]+))?)*)\s*(\/?)(>|&gt;)/g, 
      (match, open, slash, tagName, attrs, endSlash, close) => {
        // 处理属性
        const highlightedAttrs = attrs.replace(/([\w\-:]+)(\s*=\s*)((?:"[^"]*"|'[^']*'|[\w\-]+))/g, 
          '<span class="attribute">$1</span>$2<span class="string">$3</span>');
        
        return `${open}<span class="tag">${slash}${tagName}</span>${highlightedAttrs}${endSlash}${close}`;
      })
    // 处理注释
    .replace(/(&lt;!--|<!--)([\s\S]*?)(-->|--&gt;)/g, 
      '<span class="comment">$1$2$3</span>');
  
  return <span dangerouslySetInnerHTML={{ __html: highlightedCode }} />;
};

const GenerateCode: React.FC = () => {
  const { analysisResult, setAnalysisResult } = useAnalysisStore();
  const [previewVisible, setPreviewVisible] = useState(false);
  const [localHtml, setLocalHtml] = useState(analysisResult?.html || '');
  const [previousHtml, setPreviousHtml] = useState('');
  const [displayHtml, setDisplayHtml] = useState(analysisResult?.html || '');
  const [aiPrompt, setAiPrompt] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isPreviewLoading, setIsPreviewLoading] = useState(false);
  const [autoSaveIndicator, setAutoSaveIndicator] = useState('');
  
  // Editor-related states
  const editorRef = useRef<ReactCodeMirrorRef>(null);
  const editorContainerRef = useRef<HTMLDivElement>(null);
  const [activeSelection, setActiveSelection] = useState<string>('');
  const [activeSelectionRange, setActiveSelectionRange] = useState<{ from: number, to: number } | null>(null);
  
  // 临时编辑器状态
  const [tempEditingHtml, setTempEditingHtml] = useState('');
  const [shouldUpdatePreview, setShouldUpdatePreview] = useState(true);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationStatusText, setGenerationStatusText] = useState('');

  // 创建防抖保存函数
  const debouncedSaveHtml = useCallback(
    debounce((html: string) => {
      setAnalysisResult({ ...analysisResult, html });
      setAutoSaveIndicator('已自动保存');
      // 3秒后清除保存提示
      setTimeout(() => {
        setAutoSaveIndicator('');
      }, 3000);
    }, 1500), // 1.5秒后自动保存
    [analysisResult, setAnalysisResult]
  );

  // 使用防抖更新预览，避免每次输入都刷新iframe
  useEffect(() => {
    // 如果AI正在生成代码中，则跳过这个预览更新（因为我们会直接设置displayHtml）
    if (isGenerating) return;
    
    // 如果不应该更新预览（例如其他情况），则不执行更新
    if (!shouldUpdatePreview) return;
    
    setIsPreviewLoading(true);
    // 清空显示内容
    setDisplayHtml('');
    
    const timer = setTimeout(() => {
      setDisplayHtml(localHtml);
      setIsPreviewLoading(false);
    }, 500); // 500ms延迟
    
    return () => clearTimeout(timer);
  }, [localHtml, shouldUpdatePreview, isGenerating]);
  
  // 当本地HTML变化时，触发防抖保存
  useEffect(() => {
    if (localHtml !== analysisResult?.html) {
      debouncedSaveHtml(localHtml);
    }
  }, [localHtml, debouncedSaveHtml, analysisResult]);

  // 自动滚动到编辑器底部的效果
  useEffect(() => {
    if (isGenerating && editorContainerRef.current) {
      // 使用requestAnimationFrame确保在重绘前执行滚动操作
      requestAnimationFrame(() => {
        if (editorContainerRef.current) {
          // 滚动容器到底部
          editorContainerRef.current.scrollTop = editorContainerRef.current.scrollHeight;
        }
      });
    }
  }, [tempEditingHtml, isGenerating]);

  const handleEditorUpdate = (viewUpdate: any) => {
    const selection = viewUpdate.state.selection.main;
    // Persist the selection details if a selection is made
    if (!selection.empty) {
      const selectedText = viewUpdate.state.doc.sliceString(selection.from, selection.to);
      setActiveSelection(selectedText);
      setActiveSelectionRange({ from: selection.from, to: selection.to });
    } else {
      // Clear persisted selection if selection is cleared in the editor
      setActiveSelection('');
      setActiveSelectionRange(null);
    }
  };

  const handlePreviewExpand = () => {
    setPreviewVisible(true);
  };

  // 处理流式响应更新
  const handleStreamUpdate = (partialResponse: string) => {    
    // 处理可能存在的换行符和 [DONE] 标记
    const formattedResponse = partialResponse
      .replace(/\\n/g, '\n')
      .replace(/\[DONE\]/g, '');
    
    // 直接更新临时编辑器内容
    if (formattedResponse && !formattedResponse.startsWith('正在处理您的请求...')) {
      setTempEditingHtml(formattedResponse);
      
      // 在生成过程中更新预览内容
      if (isGenerating) {
        // 临时更新预览
        setDisplayHtml(formattedResponse);
      }
    }
  };

  // 处理流式响应错误
  const handleStreamError = (error: Error) => {
    setGenerationStatusText(`生成失败: ${error.message}`);
    // 重新启用预览更新
    setShouldUpdatePreview(true);
  };

  const handleAiPrompt = async () => {
    if (!aiPrompt.trim()) {
      message.error('请输入您的指令');
      return;
    }

    setPreviousHtml(localHtml); // 保存修改前的代码
    
    // 设置状态
    setIsLoading(true);
    setIsGenerating(true);
    setGenerationStatusText('AI正在生成代码，预览将在完成后更新...');
    setShouldUpdatePreview(false); // 禁止预览更新，直到生成完成
    setTempEditingHtml(localHtml); // 初始化临时编辑内容

    try {
      let modifiedHtml = '';
      
      if (activeSelection && activeSelectionRange) {
        // --- 局部修改 ---
        const modifiedSnippet = await AIService.modifyHtmlSnippet(
          activeSelection, 
          aiPrompt, 
          handleStreamUpdate
        );
        
        // 将修改后的片段替换回原文
        modifiedHtml = localHtml.slice(0, activeSelectionRange.from) + 
                       modifiedSnippet + 
                       localHtml.slice(activeSelectionRange.to);
      } else {
        // --- 全局修改 ---
        modifiedHtml = await AIService.modifyHtml(
          localHtml, 
          aiPrompt, 
          handleStreamUpdate
        );
      }

      // 设置临时编辑内容，用于在确认前展示
      setTempEditingHtml(modifiedHtml);
      
      // 临时更新预览内容，让用户在确认前看到效果
      setDisplayHtml(modifiedHtml);
      
      // 确保没有 [DONE] 标记
      const cleanedHtml = modifiedHtml.replace(/\[DONE\]/g, '');
      
      // 显示预览并询问用户是否接受修改
      Modal.confirm({
        title: 'AI已完成代码生成',
        content: (
          <div>
            <p>请查看生成的代码效果，是否接受这个修改？</p>
            
            {/* 在弹窗中添加预览效果 */}
            <div style={{ marginTop: '10px', border: '1px solid #f0f0f0', borderRadius: '4px', overflow: 'hidden', maxHeight: '400px' }}>
              <iframe
                srcDoc={wrapHtmlWithNoClickStyle(cleanedHtml)}
                style={{
                  width: '100%',
                  height: '400px',
                  border: 'none',
                  outline: 'none',
                  backgroundColor: 'white'
                }}
              />
            </div>
          </div>
        ),
        width: '70%',
        okText: '接受修改',
        cancelText: '回退到原始代码',
        onOk: () => {
          // 用户接受修改，应用到实际HTML
          setLocalHtml(modifiedHtml);
          message.success('已应用AI生成的代码');
          setAiPrompt('');
          setGenerationStatusText('生成完成，已应用');
        },
        onCancel: () => {
          // 用户拒绝修改，恢复原始代码
          setTempEditingHtml(previousHtml);
          // 恢复预览为原始内容
          setDisplayHtml(previousHtml);
          message.info('已恢复到原始代码');
          setGenerationStatusText('已取消生成');
        },
        afterClose: () => {
          // 弹窗关闭后的处理
          setIsGenerating(false);
          setShouldUpdatePreview(true); // 重新启用预览更新
        }
      });
      
    } catch (error: any) {
      console.error('AI处理错误:', error);
      message.error(`AI处理失败: ${error.message}`);
      handleStreamError(error);
      setIsGenerating(false);
      setShouldUpdatePreview(true);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.contentContainer}>
        <div className={styles.editorSection}>    
          {/* 编辑器区域 */}
          <div className={styles.editorContainer}>
            <div className={styles.editorHeader}>
              <h3>HTML编辑器</h3>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                {isGenerating && (
                  <div className={styles.generatingIndicator}>
                    <SyncOutlined spin className={styles.generatingIcon} />
                    <span>{generationStatusText}</span>
                  </div>
                )}
                {autoSaveIndicator && (
                  <div className={styles.autoSaveIndicator}>
                    {autoSaveIndicator}
                  </div>
                )}
              </div>
            </div>
            <div className={styles.editorWrapper} ref={editorContainerRef}>
              <Spin spinning={isLoading && !isGenerating} tip="AI正在处理...">
                <div className={styles.codeMirrorContainer}>
                  <CodeMirror
                    ref={editorRef}
                    value={isGenerating ? tempEditingHtml : localHtml}
                    height="100%"
                    minHeight="300px"
                    theme={vscodeDark}
                    extensions={[html()]}
                    onChange={(value) => {
                      if (!isGenerating) {
                        setLocalHtml(value);
                      }
                    }}
                    onUpdate={handleEditorUpdate}
                    readOnly={isLoading}
                    basicSetup={{
                      lineNumbers: true,
                      foldGutter: true,
                      dropCursor: true,
                      allowMultipleSelections: true,
                      indentOnInput: true,
                      highlightActiveLine: true,
                      highlightSelectionMatches: true,
                      closeBrackets: true,
                    }}
                  />
                </div>
              </Spin>
            </div>
          </div>

           {/* AI交互输入区域 */}
           <div className={styles.aiAssistantSection}>
            <div className={styles.aiAssistantHeader}>
              <RobotOutlined className={styles.aiIcon} />
              <Text strong>AI编辑助手</Text>
              <Tooltip title="代码会直接在编辑器中生成，预览会在生成完成后更新">
                <InfoCircleOutlined style={{ marginLeft: '8px', color: '#1890ff' }} />
              </Tooltip>
              <Text type="secondary" style={{ marginLeft: 'auto', fontSize: '12px' }}>
                流式响应
              </Text>
            </div>
            <div className={styles.aiPromptContainer}>
              <TextArea
                value={aiPrompt}
                onChange={e => setAiPrompt(e.target.value)}
                placeholder="输入指令进行全局修改，或选中代码进行局部修改"
                className={styles.aiPrompt}
                disabled={isLoading}
                autoSize={{ minRows: 2, maxRows: 4 }}
              />
              <Button 
                type="primary" 
                icon={<SendOutlined />} 
                onClick={handleAiPrompt} 
                loading={isLoading}
                className={styles.sendButton}
              >
                发送
              </Button>
            </div>
          </div>
        </div>

        <div className={styles.previewContainer}>
          <div className={styles.previewHeader}>
            <h3>预览</h3>
            {isGenerating && (
              <div className={styles.previewWaitingMsg}>
                <SyncOutlined spin style={{ marginRight: '5px' }} />
                正在等待生成完成...
              </div>
            )}
            <Button 
              type="text" 
              icon={<ExpandOutlined />} 
              onClick={handlePreviewExpand}
              title="全屏预览"
            />
          </div>
          <div className={styles.previewContent}>
            <Spin spinning={isPreviewLoading && !isGenerating} tip="加载预览中..." style={{height: '100%'}}>
              {(!isPreviewLoading || isGenerating) && (
                <iframe
                  srcDoc={wrapHtmlWithNoClickStyle(displayHtml)}
                  className={styles.previewFrame}
                  width="100%"
                  height="100%"
                />
              )}
              {isPreviewLoading && !isGenerating && (
                <div className={styles.loadingContainer}>
                  {/* 加载中时显示空白区域 */}
                </div>
              )}
            </Spin>
          </div>
        </div>
      </div>
      
      <Modal
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        width="80%"
        styles={{
          body: {
            height: 'calc(100vh - 200px)',
            padding: 0,
            overflow: 'hidden'
          }
        }}
        footer={null}
        style={{ top: 20}}
      >
        <iframe
          srcDoc={wrapHtmlWithNoClickStyle(displayHtml)}
          style={{
            width: '100%',
            height: '100%',
            border: 'none',
            outline: 'none',
            backgroundColor: 'white',
            display: 'block',
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0
          }}
        />
      </Modal>
    </div>
  );
};

export default GenerateCode;